﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using WebBrowserTest.Utility;
using WebBrowserTest.Analyzers;
using WebBrowserTest.AnalyzeResults;
using System.Web;
namespace WebBrowserTest
{
    public class PageAnalyzer
    {
        private string _analyzedPage;
        #region Constants
        public struct Constants
        {
            public static readonly string BackLinksUrl = "backlinkUrl";
            public static readonly string GoogleIndexUrl = "googleIndexUrl";
            public static readonly string GoogleCacheUrl = "googleCacheUrl";
            public static readonly string DmozDirUrl = "dmozDirUrl";
            public static readonly string DomainAgeUrl = "domainAgeUrl";
            public static readonly string UniqueContentUrl = "uniqueContentUrl";

        } 
        public PageAnalyzer()
        {

        }

        public string AnalyzedPage
        {
            get { return _analyzedPage; }
            set { _analyzedPage = value; }
        }

        #endregion
        public MainAnalyzerResults GetAnalyseResult(string url, string keyword, ListViewRowItem rowItem)
        {
             
            int progress = 1;
            int start = Environment.TickCount;
            //url = HttpUtility.UrlDecode(url);
            //keyword = HttpUtility.UrlDecode(keyword);
            if(!url.Contains("http://"))
            {
                url = string.Format("http://{0}",url);
            }
            string currentUri = url;
            MainAnalyzerResults mainResults = new MainAnalyzerResults();

            mainResults.Domain = url;
            mainResults.CheckDate = DateTime.Now;
            mainResults.Keyword = keyword;
            //BackLinks
            string backLinksPageContent = GetPageContent(Constants.BackLinksUrl, url);
            BackLinksAnalyzer blAnalyzer = new BackLinksAnalyzer();
            mainResults.BackLinks =
                (blAnalyzer.GetAnalyseResult(backLinksPageContent, currentUri) as DefaultResult).Value;
            rowItem.UpdateProgressBar(progress);

            //PageRank
            GooglePageRankAnalyzer gPRAnalyzer = new GooglePageRankAnalyzer();
            mainResults.PageRank = (gPRAnalyzer.GetAnalyseResult("", currentUri) as DefaultResult).Value;
            rowItem.UpdateProgressBar(progress);
            //Site
            GoogleIndexAnalyzer gIAnalyzer = new GoogleIndexAnalyzer();
            string gIUrl = new Uri(url).Host;
            if(!gIUrl.Contains("http://"))
            {
                gIUrl = string.Format("http://{0}",gIUrl);
            }
            string googleIndexContent = GetPageContent(Constants.GoogleIndexUrl, gIUrl);
            mainResults.Site = (gIAnalyzer.GetAnalyseResult(googleIndexContent, currentUri) as DefaultResult).Value;
            rowItem.UpdateProgressBar(progress);
            //Google Cache
            GoogleCacheAnalyzer gCAnalyzer = new GoogleCacheAnalyzer();
            string googleCacheContent = GetPageContent(Constants.GoogleCacheUrl, url);
            if (googleCacheContent != string.Empty)
            {
                mainResults.CacheAge =
                    (gCAnalyzer.GetAnalyseResult(googleCacheContent, currentUri) as GoogleCacheResult).GetCacheTimeStamp;
            }
            else
            {

                mainResults.CacheAge = -1;
            }
            rowItem.UpdateProgressBar(progress);
            //DMOZ
            string dmozUrl = new Uri(url).Host;
            if(!dmozUrl.Contains("http://"))
            {
                dmozUrl = string.Format("http://{0}",dmozUrl);
            }
            string dmozContent = GetPageContent(Constants.DmozDirUrl, dmozUrl);
            DmozAnalyzer dMozAnalyzer = new DmozAnalyzer();
            mainResults.Dmoz = (dMozAnalyzer.GetAnalyseResult(dmozContent, currentUri) as DefaultResult).Value;
            rowItem.UpdateProgressBar(progress);

            //Domain Age
            string dAgeUrl = new Uri(url).Host;
            if(!dAgeUrl.Contains("http://"))
            {
                dAgeUrl = string.Format("http://{0}", dAgeUrl);
            }
            string dAgeContent = GetPageContent(Constants.DomainAgeUrl, dAgeUrl);
            WebarchiveAnalyzer wAAnalyzer = new WebarchiveAnalyzer();
            mainResults.DomainAge = (wAAnalyzer.GetAnalyseResult(dAgeContent, currentUri) as DomainAgeAnalyzeResults).DomainAge;
            rowItem.UpdateProgressBar(progress);
                                        /*-----------Detail analyze---------------*/

            //Keyword density
            string mainDomainContent = Utils.getPageHtmlString(currentUri);
            WordDensityAnalyzer wDAnalyzer = new WordDensityAnalyzer(keyword);
            var dsResult = wDAnalyzer.GetAnalyseResult(mainDomainContent, currentUri) as DensityAnalyzerResult;
            mainResults.Density = dsResult.PercentageDensity;
            rowItem.UpdateProgressBar(progress);
            //density per tag
            WordPerTagAnalyzer wPtDensitAnalyzer = new WordPerTagAnalyzer(keyword);
            var dPTResult = wPtDensitAnalyzer.GetAnalyseResult(mainDomainContent, currentUri) as WordPerTagAnalyzeResult;
            mainResults.HTags =
                GetExistsWordInTagString(dPTResult.TagDensity["h1"] != 0 || 
                                         dPTResult.TagDensity["h2"] != 0 ||
                                         dPTResult.TagDensity["h3"] != 0);
            //url density
            mainResults.Url = GetExistsWordInTagString(dPTResult.TagDensity["url"] != 0 );
            rowItem.UpdateProgressBar(progress);
            mainResults.Title = GetExistsWordInTagString(dPTResult.TagDensity["title"] != 0);
            rowItem.UpdateProgressBar(progress);
            mainResults.Desc = GetExistsWordInTagString(dPTResult.TagDensity["description"]!=0);
            rowItem.UpdateProgressBar(progress);
            //Unique content
            string uniquePageContent = GetPageContent(Constants.UniqueContentUrl, url);
            UniqueContentAnalyzer uCAnalyzer = new UniqueContentAnalyzer();
            mainResults.Unique =
                (uCAnalyzer.GetAnalyseResult(uniquePageContent, currentUri) as UniqueContentResult).
                    UniquePercentageValue;

            //get domain ip adress
            IPAddress[] ip = null;
            try
            {
                ip = Dns.GetHostAddresses(Utils.ExtractDomainNameFromUR(url));
            }
            catch (Exception)
            {

            }
            if(ip!=null && ip.Count() > 0)
            {
                mainResults.Ip = ip[0].ToString();
            }
            mainResults.Anchor =
                (new AnchorAnalyzer().GetAnalyseResult(mainDomainContent, AnalyzedPage) as AnchorAnalyzeResult).Anchor; 

            GooglePositionAnalyzer gpAnalyzer = new GooglePositionAnalyzer();
            string googleQueryContent = GetPageContent("googlePosition", keyword);
            mainResults.GooglePosition = gpAnalyzer.GetGooglePosition(googleQueryContent, url);
            rowItem.UpdateProgressBar(progress);
            rowItem.ProcessUpdateStatusLabel();
            int end = Environment.TickCount -start;


            return mainResults;
        }

        private string GetPageContent(string configKey, string url)
        {
            return Utils.getPageHtmlString(string.Format(Utils.GetUrlFromConfiguration(configKey), url));
        }
        private string GetExistsWordInTagString(bool exists)
        {
            return exists ? "Tak" : "Nie";
        }
    }
}
